package com.laicunba.ext.activity.act20170410;

import java.util.Date;

import javax.jms.Message;
import javax.jms.TextMessage;

import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.laicunba.ext.service.SlaveUserService;
import com.laicunba.jms.JmsTopicListener;
import com.laicunba.jms.JmsTopicListenerTemplate;
import com.laicunba.pojo.UserDO;
import com.laicunba.util.CacheUtil;
import com.laicunba.util.DateUtil;
import com.laicunba.util.StringUtil;

//@Component
public class FriendRegistListener extends JmsTopicListenerTemplate implements JmsTopicListener {

	@Autowired
	private SlaveUserService slaveUserService;

	private static int HOUR24 = 3600 * 24;
	private static int MINITE10 = 600;

	@Override
	public String topic() {
		return "lcb.core.usr.create";
	}

	@Override
	public boolean receive(Message msg) {
		TextMessage txtMsg = (TextMessage) msg;
		try {

			JSONObject msgJson = (JSONObject) new JSONParser().parse(txtMsg.getText());
			if (!msgJson.containsKey("inviteFrom")) {
				return true;
			}
			String inviteFrom = (String) msgJson.get("inviteFrom");
			if (StringUtil.isEmpty(inviteFrom)) {
				return true;
			}

			// 防重复
			if (CacheUtil.incr("act.20170410." + (String) msgJson.get("id"), MINITE10) > 1) {
				return true;
			}

			UserDO userDO = slaveUserService.findByInviteCode(inviteFrom);
			if (userDO == null) {
				return true;
			}
			String key = "act.20170410chance." + userDO.getId() + DateUtil.formatDate(new Date());
			String val = CacheUtil.getAttribute(key);
			if (StringUtil.isEmpty(val)) {
				CacheUtil.setAttribute(key, "1", HOUR24);
				return true;
			}
			if (Integer.parseInt(val) >= 5) {
				return true;
			}
			CacheUtil.setAttribute(key, String.valueOf(Integer.parseInt(val) + 1), HOUR24);

		} catch (Exception e) {
			e.printStackTrace();
		}
		return true;
	}

}
